<template>
  <div class="table-page">
    <div
      class="table-search-box"
      @keyup.enter="beforeSearch()"
    >
      <div class="search-item">
        <label>学校：</label>
        <div class="table-query-input">
          <el-select
            v-model="queryData.schoolCode"
            filterable
            placeholder="请选择学校"
            remote
            :remote-method="loadXx"
            clearable
            @change="changeSchool"
          >
            <el-option
              v-for="item in schools"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            >
            </el-option>
          </el-select>
        </div>
      </div>
      <div class="search-item">
        <label>老师：</label>
        <div class="table-query-input">
          <el-select
            v-model="queryData.teacherId"
            filterable
            placeholder="请选择老师"
            remote
            :remote-method="loadXx"
            clearable
            @change="changeSchool"
          >
            <el-option
              v-for="item in teachers"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </div>
      </div>
      <div class="search-item">
        <label>专业：</label>
        <div class="table-query-input">
          <el-cascader
            :key="zeroTwo"
            ref="department"
            v-model="queryData.departmentId"
            :props="departmentProps"
            :show-all-levels="false"
            filterable
            clearable
          ></el-cascader>
        </div>
      </div>
      <div class="search-item">
        <label>题型：</label>
        <div class="table-query-input">
          <el-cascader
            ref="questionType"
            :key="zeroOne"
            v-model="questionType"
            :props="questionTypeProps"
            :show-all-levels="false"
            filterable
            clearable
          ></el-cascader>
        </div>
      </div>
      <div class="search-item">
        <label>题目内容：</label>
        <div class="table-query-input">
          <el-input
            v-model="queryData.searchKey"
            clearable
            placeholder="关键词"
          ></el-input>
        </div>
      </div>
      <div class="search-item">
        <label>难度：</label>
        <div class="table-query-input">
          <el-select
            v-model="queryData.difficulty"
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in difficultyOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </div>
      </div>
      <div class="search-item">
        <el-button
          type="primary"
          icon="el-icon-search"
          :loading="tableLoading"
          @click="beforeSearch"
        >搜索
        </el-button>
      </div>
        <div class="search-item">
            <el-button
                icon="el-icon-refresh"
                :loading="tableLoading"
                @click="resetSearch()"
            >重置
            </el-button>
        </div>
    </div>

    <div class="table-operation-box">
      <el-button
        type="danger"
        icon="el-icon-delete"
        style="margin-bottom: 2em"
        :disabled="ids.length === 0"
        @click="
                    tableDelete(
                        '/exam/question/deleted-list',
                        {
                            ids: ids
                        },
                        true
                    )
                "
      >批量删除
      </el-button>
      <el-button
        type="primary"
        icon="el-icon-unlock"
        style="margin-bottom: 2em"
        :disabled="ids.length === 0"
        @click="
                    hideList(
                        `公开`,
                        {
                            ids: ids,
                            isHide: false
                        },
                        true
                    )
                "
      >批量公开
      </el-button>
      <el-button
        type="warning"
        icon="el-icon-lock"
        style="margin-bottom: 2em"
        :disabled="ids.length === 0"
        @click="
                    hideList(
                        `隐藏`,
                        {
                            ids: ids,
                            isHide: true
                        },
                        true
                    )
                "
      >批量隐藏
      </el-button>
    </div>
    <div class="table-data-box">
      <el-table
        ref="table"
        v-loading="tableLoading"
        border
        :data="tableData"
        style="width: 100%;min-height:40em"
        row-key="id"
        :highlight-current-row="true"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          min-width="55"
          align="center"
          :resizable="false"
        >
        </el-table-column>
        <el-table-column
          type="index"
          :index="indexMethod"
          min-width="55"
          align="center"
          :resizable="false"
        >
        </el-table-column>
        <el-table-column
          prop="remark"
          label="试题内容"
          :resizable="false"
        >
          <template slot-scope="scope">
            <div>
              <p
                v-if="scope.row.isHide"
                style="color: red"
              >
                【状态】隐藏
              </p>
              <p
                v-else
                style="color: green"
              >【状态】公开</p>
            </div>
            <div>【学校】{{ scope.row.schoolName }}</div>
            <div>
              【难度】{{ difficulty[scope.row.difficulty] }}
            </div>
            <div>【题型】{{ status[scope.row.firstType] }}</div>
            <div class="questionInfo">
              【题干】
              <p v-html="scope.row.stem[0].vl"></p>
            </div>

            <div v-if="
                                status[scope.row.firstType] === '单选题' ||
                                    status[scope.row.firstType] === '多选题'
                            ">
              <div
                v-for="(item, index) in scope.row.answer"
                :key="index"
                class="questionInfo"
              >
                {{ item.option }}、
                <p v-html="item.content[0].vl"></p>
              </div>
            </div>

            <div
              v-if="status[scope.row.firstType] === '单选题'"
              class="questionInfo"
            >
              正确答案：{{ scope.row.rightAnswer }}
            </div>

            <div
              v-if="status[scope.row.firstType] === '多选题'"
              class="questionInfo"
            >
              正确答案：<span
                v-for="(item, index) in scope.row.rightAnswer"
                :key="index"
              >{{ item }}</span>
            </div>

            <div
              v-if="status[scope.row.firstType] === '判断题'"
              class="questionInfo"
            >
              正确答案：
              <span v-if="scope.row.rightAnswer === 1">正确</span>
              <span v-else>错误</span>
            </div>

            <div
              v-if="status[scope.row.firstType] === '填空题'"
              class="questionInfo"
            >
              正确答案：
              <p
                v-for="(item, index) in scope.row.rightAnswer"
                :key="index"
                v-html="item.vl[0].vl"
              ></p>
            </div>

            <div
              v-if="status[scope.row.firstType] === '简答题'"
              class="questionInfo"
            >
              正确答案：
              <p
                v-for="(item, index) in scope.row.rightAnswer"
                :key="index"
                v-html="item.vl[0].vl"
              ></p>
            </div>
            <div class="questionInfo">
              <span>试题解析：</span>
              <p v-html="scope.row.answerDesc[0].vl"></p>
            </div>
            <div
              v-if="status[scope.row.firstType] === '组合题'"
              class="questionInfo"
            >
              <hr />
              <div
                v-for="(item, index) in scope.row.children"
                :key="index"
              >
                <div>【题型】{{ status[item.firstType] }}</div>
                <div>
                  【难度】{{ difficulty[item.difficulty] }}
                </div>
                <div class="questionInfo">
                  【题干】
                  <p v-html="item.stem[0].vl"></p>
                </div>
                <div v-if="
                                        status[item.firstType] === '单选题' ||
                                            status[item.firstType] === '多选题'
                                    ">
                  <div
                    v-for="(item2, index2) in item.answer"
                    :key="index2"
                    class="questionInfo"
                  >
                    {{ item2.option }}、
                    <p v-html="item2.content[0].vl"></p>
                  </div>
                </div>

                <div
                  v-if="status[item.firstType] === '单选题'"
                  class="questionInfo"
                >
                  正确答案：{{ item.rightAnswer }}
                </div>

                <div
                  v-if="status[item.firstType] === '多选题'"
                  class="questionInfo"
                >
                  正确答案：<span
                    v-for="(item2,
                                        index2) in item.rightAnswer"
                    :key="index2"
                  >{{ item2 }}</span>
                </div>

                <div
                  v-if="status[item.firstType] === '判断题'"
                  class="questionInfo"
                >
                  正确答案：
                  <span v-if="item.rightAnswer === 1">正确</span>
                  <span v-else>错误</span>
                </div>

                <div
                  v-if="status[item.firstType] === '填空题'"
                  class="questionInfo"
                >
                  正确答案：
                  <p
                    v-for="(item2,
                                        index2) in item.rightAnswer"
                    :key="index2"
                    v-html="item2.vl[0].vl"
                  ></p>
                </div>

                <div
                  v-if="status[item.firstType] === '简答题'"
                  class="questionInfo"
                >
                  正确答案：
                  <p
                    v-for="(item2,
                                        index2) in item.rightAnswer"
                    :key="index2"
                    v-html="item2.vl[0].vl"
                  ></p>
                </div>
                <hr />
              </div>
            </div>

            <div class="questionInfo">
              <span>试题解析：</span>
              <p v-html="scope.row.answerDesc[0].vl"></p>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="createByName"
          label="老师"
          min-width="16"
        >
        </el-table-column>
        <el-table-column
          label="操作"
          width="200"
          align="center"
          fixed="right"
          :resizable="false"
        >
          <template slot-scope="scope">
            <el-button
                class="primary"
                type="text"
                size="mini"
                icon="el-icon-edit"
              :loading="scope.row.opLoading"
              @click="go('edit-question?id=' + scope.row.id)"
            >编辑
            </el-button>
            <el-button
              v-if="!scope.row.edit"
              class="danger"
              type="text"
              icon="el-icon-delete"
              size="mini"
              :loading="scope.row.opLoading"
              @click="
                                tableDelete(
                                    '/exam/question/deleted-list',
                                    {
                                        ids: [scope.row.id]
                                    },
                                    true
                                )
                            "
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-if="pageData.total" class="xy-between table-page-box">
      <el-pagination
        :current-page.sync="pageData.currentPage"
        :page-sizes="pageData.pageSizes"
        :page-size.sync="pageData.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageData.total"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { fetchQuestionType } from "@/api/exam.js";
import { TablePage } from "@/layout/mixin/iVue.js";
import { mapState } from "vuex";
import { get, put } from "@/api/request";
import {
  fetchDepartmentChildren,
  fetchFirstStageBySchoolCode
} from "@/api/user";

export default {
  name: "QuestionIndex2",
  mixins: [TablePage],
  data () {
    return {
      zeroOne: 0,
      zeroTwo: 0,
      options: [
        {
          value: "singleChoice",
          label: "单选题"
        },
        {
          value: "multipleChoice",
          label: "多选题"
        },
        {
          value: "judgment",
          label: "判断题"
        },
        {
          value: "fill",
          label: "填空题"
        },
        {
          value: "text",
          label: "简答题"
        },
        {
          value: "combination",
          label: "组合题"
        }
      ],
      difficultyOptions: [
        {
          value: "easy",
          label: "简单"
        },
        {
          value: "normal",
          label: "普通"
        },
        {
          value: "difficult",
          label: "困难"
        }
      ],
      questionType: [],
      queryData: {
        queryType: 2,
        firstType: null,
        secondTypeId: null,
        difficulty: null,
        searchKey: null,
        schoolCode: null,
        departmentId: null,
        teacherId: null
      },
      schoolCode: null,
      secondQueryData: {
        firstType: null
      },
      schools: null,
      teachers: null,

      department: null,
      tableData: [],
      ids: [],
      questionTypeProps: {
        lazy: true,
        checkStrictly: true,
        lazyLoad: this.fetchQuestionType
      },
      departmentProps: {
        lazy: true,
        checkStrictly: true,
        emitPath: false,
        lazyLoad: this.fetchDepartment
      }
    };
  },
  computed: {
    ...mapState({
      status: state => state.status.questionFirstType,
      difficulty: state => state.status.questionDifficulty
    })
  },
  watch: {
    actionSearch (val) {
      this.$refs.tree.filter(val);
    }
  },
  created () {
    this.loadXx();
  },
  methods: {
    clearQuery () {
      this.questionType = [];
      this.resourceType = null;
      this.queryData = {};
      this.chapterId = null;
      this.paperType = null;
      this.questionPaperId = null;
      this.search();
    },
    beforeSearch () {
      if (this.questionType.length === 1) {
        this.queryData.firstType = this.questionType[0];
      } else if (this.questionType.length === 2) {
        this.queryData.firstType = this.questionType[0];
        this.queryData.secondTypeId = this.questionType[1];
      } else {
        this.queryData.firstType = null;
        this.queryData.secondTypeId = null;
      }
      this.search();
    },
    indexMethod (index) {
      return (
        index +
        1 +
        (this.pageData.currentPage - 1) * this.pageData.pageSize
      );
    },
    search (queryData) {
      this.loadTable("/exam/question/page", queryData);
    },
    handleSelectionChange (val) {
      this.ids = [];
      const length = val.length;
      for (let n = 0; n < length; n++) {
        this.ids.push(val[n].id);
      }
    },
    //获取学校信息
    loadXx (query) {
      get("/user/cu/teacher/page-schoolCode", {
        current: 1,
        size: 10000
      }).then(res => {
        this.teachers = res.records
      });
      return get("/user/sys/school/list", {
        name: query,
        noVip: true
      }).then(res => {
        this.schools = res;
        return res;
      });
    },
    //级联题型
    fetchQuestionType (node, resolve) {
      const { level } = node;
      if (level === 0) {
        const nodes = Array.from(this.options).map(item => {
          return {
            value: item.value,
            label: `${item.label}`,
            leaf: false
          };
        });
        resolve(nodes);
      } else if (level === 1) {
        fetchQuestionType({ firstType: node.data.value }).then(res => {
          const nodes = Array.from(res).map(item => {
            return {
              value: item.id,
              label: `${item.viewName}`,
              leaf: true
            };
          });
          resolve(nodes);
        });
      } else {
        const nodes = null;
        resolve(nodes);
      }
    },
    // //专业改变时
    // changeDepartment(departmentId) {
    //     this.getTeacher(departmentId, null);
    // },
    //学校改变时
    changeSchool (schoolCode) {
      this.schoolCode = schoolCode;
      this.queryData.departmentId = [];
      ++this.zeroTwo;
      // this.getTeacher(null, schoolCode);
    },
    //获取学校专业
    fetchDepartment (node, resolve) {
      let schoolCode = this.schoolCode;
      const { level } = node;
      if (this.schoolCode !== null) {
        if (!node.data) {
          fetchFirstStageBySchoolCode({
            schoolCode: schoolCode,
            type: "xklb"
          }).then(res => {
            const nodes = Array.from(res).map(item => {
              return {
                value: item.id,
                label: `${item.name}`,
                leaf:
                  level >= (item.children.length > 0 ? 1 : 0)
              };
            });
            resolve(nodes);
          });
        } else {
          fetchDepartmentChildren({ id: node.data.value }).then(
            res => {
              const nodes = Array.from(res).map(item => {
                return {
                  value: item.id,
                  label: `${item.name}`,
                  leaf:
                    level >=
                    (item.children.length > 0
                      ? level + 1
                      : 0)
                };
              });
              resolve(nodes);
            }
          );
        }
      }
    },
    //清除专业下拉框
    cleanDepartmentId () {
      delete this.queryData.departmentId;
    },
    //清除老师下拉框
    cleanTeacher () {
      delete this.queryData.teacherId;
    },
    //获取老师
    getTeacher (departmentId, schoolCode) {
      //TODO 获取老师
    },
    //批量公开或隐藏
    hideList (type, data, alter, callback, errorMessage) {
      const work = () => {
        return put(`/exam/question/hide-list`, data, errorMessage)
          .then(r => {
            this.$message.success("设置成功");
            if (typeof callback === "function") callback(r);
            else this.search();
          })
          .catch(e => {
            console.error("error:", e);
            this.$message.fail("设置失败");
          });
      };
      if (alter) {
        this.$confirm("是否批量标记为" + type + "？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            work();
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消"
            });
          });
      } else {
        work();
      }
    },
    filterAction (value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    clickSelectAction (data, checked, indeterminate) {
      const actionCode = data.id;
      if (checked) {
        this.dataForm.actionCodes.push(actionCode);
      } else {
        this.dataForm.actionCodes.splice(
          this.dataForm.actionCodes.indexOf(actionCode),
          1
        );
      }
    }
  }
};
</script>

<style lang="scss" scoped>
p {
  display: inline-table;
}
</style>
